package cn.k.controller;

import cn.k.domain.Business;
import cn.k.qo.BusinessQueryObject;
import cn.k.qo.QueryObject;
import cn.k.service.IBusinessService;
import cn.k.service.IRoleService;
import cn.k.util.FileUploadUtil;
import cn.k.util.RequirePermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/business")
public class BusinessController {

    @Autowired
    private IBusinessService businessService;

    @Autowired
    private IRoleService roleService;

    //处理分页查询页面请求
    @RequestMapping("/list")
    @RequirePermission(name = "门店查询", expression = "business:list")
    public String list(@ModelAttribute("qo") BusinessQueryObject qo, Model model) {
        PageInfo<Business> pageInfo = businessService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        return "business/list";
    }


    //处理删除请求
    @RequirePermission(name = "门店删除", expression = "business:delete")
    @RequestMapping("/delete")
    public String delete(Long id) {
        if (id != null) {
            businessService.delete(id);
        }
        return "redirect:/business/list";
    }

    @RequestMapping("/input")
    public String input(Long id,Model model){
        if (id!=null){
            Business business = businessService.get(id);
            model.addAttribute("business",business);
        }
        return "/business/input";
    }


    //处理添加或者更新的请求
    @RequirePermission(name ="门店编辑",expression = "business:saveOrUpdate")
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Business business, MultipartFile file, HttpServletRequest request) throws Exception {
        if (file!=null &&file.getSize()>0){
            String path = request.getServletContext().getRealPath("/");
            System.out.println(path);
            String uploadFile = FileUploadUtil.uploadFile(file, path);
            business.setLicenseImg(uploadFile);

        }

        //判断有没有id
        if (business.getId()==null){
            businessService.insert(business);
        }else {
            businessService.update(business);
        }
        return "redirect:/business/list";
    }


}
